﻿/*
 * Autore: Artur Tolstenco
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using RecipesManager.Data;
using RecipesManager.MainControls.GenericUserControls;
using RecipesManager.MainControls.IngredientSubControls;

namespace RecipesManager.MainControls
{
    /// <summary>
    /// Interaction logic for IngredientUserControl.xaml
    /// </summary>
    public partial class IngredientUserControl : IMyUserControls, ISwitchable
    {
        readonly IngredientMainPane _panel;
        readonly LeftSideListUserControl _leftList;
        bool _refreshing;
        readonly ListBox _lbItems;
        readonly Button _btCancella;
        readonly TextBox _tbSearch;


        public string SectionName { get { return (string)Application.Current.FindResource("IngredientsSectionLabel"); } }

        public IngredientUserControl()
        {
            InitializeComponent();
            _leftList = new LeftSideListUserControl {UsedBy = this};
            
            /* left side list */
            leftSideList.Content = _leftList;

            _lbItems = _leftList.lb_items;
            _btCancella = _leftList.bt_delete;
            _tbSearch = _leftList.tb_search;


            Refresh_Ingredient_List();
            _panel = new IngredientMainPane();

            CommandManager.RegisterClassCommandBinding(typeof(IngredientUserControl), _savebinding);
            CommandManager.RegisterClassCommandBinding(typeof(IngredientUserControl), _closebinding);
        }

        void Refresh_Ingredient_List()
        {
            Mouse.OverrideCursor = Cursors.Wait;
            _refreshing = true;
            var selectedItem = _lbItems.SelectedItem as string;
            _lbItems.Items.Clear();
            foreach (var ingredient in Manager.Ingredients.Where(i => i.Name.ToLower().Contains(_tbSearch.Text.ToLower())))
                _lbItems.Items.Add(ingredient.Name);
            _lbItems.SelectedItem = selectedItem;
            _refreshing = false;
            Mouse.OverrideCursor = null;
        }


        public bool Save_Context()
        {
            if (_panel.Editing)
            {
                if (_panel.IsModified())
                {
                        //"Vuoi salvare le modifiche?"
                    var result = MessageBox.Show((string)Application.Current.FindResource("want_to_save"),
                                                 (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.YesNoCancel,
                                                 MessageBoxImage.Warning);

                    switch (result)
                    {
                        case MessageBoxResult.Yes:
                            Mouse.OverrideCursor = Cursors.Wait;

                            var r = _panel.SaveCurrentIngredient();

                            Mouse.OverrideCursor = null;
                            return r;
                        case MessageBoxResult.No:
                            break;
                        case MessageBoxResult.Cancel:
                            return false;
                    }
                }
                return true;
            }
            return true;
        }


        #region ISwitchable Members

        public void UtilizeState(object state)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region ButtonHandlers

        public void Bt_Back_Click(object sender, RoutedEventArgs e)
        {
            if (!Save_Context()) return;
            
            Manager.ClearCache();
            Switcher.Switch(new MainMenu());
        }

        public void Bt_Delete_Click(object sender, RoutedEventArgs e)
        {
            var currentIngredient = _lbItems.SelectedItem as string;

            if (currentIngredient == null) return;

            IEnumerable<string> canDeleteMessage;
            var canDelete = Data.Operations.Operations.CanRemoveIngredient(currentIngredient, out canDeleteMessage);
            var msgFromCanRemove = canDeleteMessage.Aggregate("", (current, m) => current + (Environment.NewLine + m));

            var msgStr = "";

            if (canDelete)
            {
                msgStr += (string) Application.Current.FindResource("ElementCanBeDeleted");
                if (!msgFromCanRemove.Equals(""))
                    msgStr += " " + (string) Application.Current.FindResource("ElementIsUsedBy") + msgFromCanRemove;
                
                var result = MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.YesNo,
                                                MessageBoxImage.Warning);

                switch (result)
                {
                    case MessageBoxResult.Yes:
                        Mouse.OverrideCursor = Cursors.Wait;

                        Manager.Ingredients.Remove(currentIngredient);

                        _panel.Editing = false;

                        _refreshing = true;
                        _lbItems.SelectedItem = null;
                        _lbItems.Items.Remove(currentIngredient);
                        _refreshing = false;

                        ingredientContentPane.Content = null;

                        Mouse.OverrideCursor = null;
                        break;
                    case MessageBoxResult.No:
                        break;
                }
            }
            else
            {
                msgStr = (string) Application.Current.FindResource("ElementCannotBeDeleted") + msgFromCanRemove;
                MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.OK,
                                                MessageBoxImage.Warning);
            }

        }

        public void Bt_Add_Click(object sender, RoutedEventArgs e)
        {
            if (!Save_Context()) return;

            _refreshing = true;
            _lbItems.SelectedItem = null;
            _refreshing = false;

            _panel.CurrentIngredientName = "";

            if (ingredientContentPane.Content == null)
                ingredientContentPane.Content = _panel;
        }

        public void Bt_Search_Click(object sender, RoutedEventArgs e)
        {
            Refresh_Ingredient_List();
        }


        public void Bt_Clear_Search_Click(object sender, RoutedEventArgs e)
        {
            _tbSearch.Text = "";
            Refresh_Ingredient_List();
        }

        public void Lb_Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _btCancella.IsEnabled = _lbItems.SelectedItem != null;

            if (_refreshing) return;

            if (Save_Context())
            {
                Refresh_Ingredient_List();
                _panel.CurrentIngredientName = (string)_lbItems.SelectedValue;
            }

            if (ingredientContentPane.Content == null)
                ingredientContentPane.Content = _panel;
        }

        #endregion

        #region SaveCommandRegion

        readonly CommandBinding _savebinding = new CommandBinding(ApplicationCommands.Save, CommandSaveHandler);

        static void CommandSaveHandler(object target, ExecutedRoutedEventArgs e)
        {
            var t = ((IngredientUserControl) target);
            if (t == null)
                return;
            Mouse.OverrideCursor = Cursors.Wait;

            if (t._panel.SaveCurrentIngredient())
            {
                t.Refresh_Ingredient_List();
                if  (t._panel.Editing)
                {
                    t._refreshing = true;
                    t._lbItems.SelectedItem = t._panel.CurrentIngredientName;
                    t._refreshing = false;
                }
            }

            Mouse.OverrideCursor = null;

        }

        #endregion

        #region CloseCommandRegion

        readonly CommandBinding _closebinding = new CommandBinding(ApplicationCommands.Close, CommandCloseHandler);

        static void CommandCloseHandler(object target, ExecutedRoutedEventArgs e)
        {
            var t = ((IngredientUserControl)target);
            if (t == null)
                return;

            if (!t.Save_Context()) return;

            t._panel.Editing = false;

            t._refreshing = true;
            t._lbItems.SelectedItem = null;
            t._refreshing = false;

            t.ingredientContentPane.Content = null;
            t.Refresh_Ingredient_List();
        }

        #endregion
    }
}